package com.duck.user.controller;

import com.duck.user.utils.RedisUtils;
import com.duck.common.domain.Result;
import com.duck.user.domain.dto.RegisterDto;
import com.duck.user.domain.po.UserPojo;
import com.duck.user.domain.po.UserRolePojo;
import com.duck.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 用户注册
     *
     * @param user 前端传递值
     * @return 状态码以及相关信息
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/register/")
    public Result register(@RequestBody @NotNull RegisterDto user) {
        //校验用户名是否重复
        UserPojo i = userService.checkUserByUsername(user.getUsername());
        if (i != null && i.getUsername() != null) {
            return new Result(404, "用户名已存在，请登录账号或替换名称");
        }
        //校验密码
        if (!user.getPassword().equals(user.getVerifyPassword())) {
            return new Result(404, "两次密码输入不一致");
        }
        //校验邮箱是否重复
        UserPojo a = userService.checkEmail(user.getEmail());
        if (a != null && a.getEmail() != null) {
            return new Result(404, "邮箱已存在，请替换邮箱");
        }
        //从redis中取出邮箱的对应验证码
        String verifyCode = redisUtils.getValue(user.getEmail());
        if (!user.getCode().equals(verifyCode)) {
            return new Result(404, "验证码输入错误或验证码已过期");
        }
        String avatar = "https://interview-agent.oss-cn-beijing.aliyuncs.com/8c82eb85-2550-449d-8498-1affd8bb206c.jpg";
        //校验身份，用户身份，0代表农户，1为公司，2为专家
        //新增用户
        HashMap<String, Object> insertParameter = new HashMap<>() {{
            put("username", user.getUsername());
            put("email", user.getEmail());
            put("password", BCrypt.hashpw(user.getPassword(), BCrypt.gensalt())); //密码加密
            put("userType", user.getIdentify());//身份
            put("province", user.getProvince());
            put("city", user.getCity());
            put("district", user.getDistrict());
            put("avatar",avatar);
        }};
        userService.addUser(insertParameter);
        //用户角色表新增
        UserPojo farmer = userService.checkUserByUsername(user.getUsername());
        UserRolePojo userRole = new UserRolePojo();
        userRole.setUserId(String.valueOf(farmer.getUserId()));
        userRole.setRoleId(user.getIdentify());
        userService.insertUserRole(userRole);
        return new Result(200, "注册成功");
    }
}
